﻿using IWshRuntimeLibrary;
using Microsoft.Win32;
using Panuon.WPF.UI;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using System.Windows;


namespace MCPlatform.Components
{
    public class AutoStartup
    {
        public static bool SetAutoStart(bool enable)
        {
            try
            {
                // 获取应用程序的名称和路径
                string appName = Process.GetCurrentProcess().ProcessName; // 自动获取当前运行的应用程序名称; 
                string applicationPath = Assembly.GetExecutingAssembly().Location;
                string exeDir = System.IO.Path.GetDirectoryName(applicationPath) + "\\" + appName + ".exe";

                string? appDirectory = Path.GetDirectoryName(applicationPath);


                //获取自启动文件夹路径
                string startupFolderPath = Environment.GetFolderPath(Environment.SpecialFolder.Startup);
                string shortcutPath = Path.Combine(startupFolderPath, $"{appName}.lnk");

                // 判断目标文件夹是否已有快捷方式，存在则覆盖
                if (System.IO.File.Exists(shortcutPath))
                {
                    System.IO.File.Delete(shortcutPath);
                }

                // 创建快捷方式
                if (enable)
                {
                    WshShell shell = new WshShell();
                    IWshShortcut shortcut = (IWshShortcut)shell.CreateShortcut(shortcutPath);
                    shortcut.Description = "Auto Startup Shortcut";
                    shortcut.TargetPath = exeDir;
                    shortcut.WorkingDirectory = appDirectory;
                    shortcut.Save();
                }
               

                return true;
            }
            catch (Exception)
            {
                return false;
               // throw;
            }
          
        }
    }
}
